<template>
  <div>
      <table>
          <tr>
              <td>id</td>
              <td>图书名</td>
              <td>操作</td>
          </tr>
          <tr v-for="i in tushu" :key="i.id">
              <td>{{i.id}}</td>
              <td>{{i.name}}</td>
              <td><button @click="bug(i.id,i.name,i.price)">购买</button></td>
          </tr>
      </table>
  </div>
</template>

<script>
import axios from 'axios'
export default {
    data() {
        return {
           tushu:[], 
        }
    },methods: {
        yamadie(){
            axios({
                url:"http://127.0.0.1:8000/tushulist",
                method:"post"
            }).then(resp=>{
                this.tushu = resp.data
            })
        },
        bug(pid,name,price){  
            var uid = sessionStorage.getItem("uid")
            if(uid==null){
                alert("您还没登录,请去登录")
                this.$router.push({"path":"/shanglogin","query":{"next_path":"/tushulist"}})
            }{
                //购买，添加到购物车（商品id,用户id,商品个数）
                //先去读取 用户添加的购物车记录
                let carts = sessionStorage.getItem(uid)
                //把购物记录转成JSON对象
                carts = JSON.parse(carts)
                if(carts==null){
                    carts=[]
                }
                let flag = true
                for(let i=0;i<carts.length;i++){
                    if(carts[i].pid==pid){
                        carts[i].num+=1
                        flag=false
                        break
                    }
                }
                if(flag){
                    const cart = {"pid":pid,"num":1,"name":name,"price":price}
                    //把购物的商品添加到购物车列表中
                    carts.push(cart)
                }
                
                sessionStorage.setItem(uid,JSON.stringify(carts))
                
            }
        },
        
    },created() {
        this.yamadie()
    }
}
</script>

<style>

</style>